<template>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed prop="cleaningId" label="清洗编号" width="100" />
        <el-table-column prop="itemName" label="设备名称" width="100" />
        <el-table-column prop="itemCause" label="清洗原因" width="100" />
        <el-table-column prop="planTime" label="时间" width="100" />
        <el-table-column prop="cleaningStaff" label="清洗人员" width="100" />
        <el-table-column prop="remark" label="备注" width="100" />
        <el-table-column fixed="right" label="操作列" min-width="100">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleClick(scope.row)">
                    Detail
                </el-button>
                <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
                    修改
                </el-button>
                <el-button link type="danger" size="small" @click="handleDelete(scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
        <el-pagination v-model:current-page="page.pageindex" v-model:page-size="page.pageSize"
            :page-sizes="[1, 2, 3, 4]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
        <el-form :model="form" :rules="rules" ref="formRef">
            <el-form-item label="设备名称" prop="itemName">
                <el-select v-model="form.itemName" placeholder="请选择设备名称">
                    <el-option v-for="item in getshebeilist" :key="item.id" :label="item.equipment_Name"
                        :value="item.equipment_Name" />
                </el-select>
            </el-form-item>
            <el-form-item label="清洗原因" prop="itemCause">
                <el-input v-model="form.itemCause" type="textarea" placeholder="请输入清洗原因" />
            </el-form-item>
            <el-form-item label="时间:单位/小时" prop="planTime">
                <span><el-input v-model="form.planTime" /></span>
            </el-form-item>
            <el-form-item label="清洗人员" prop="cleaningStaff">
                <el-select v-model="form.cleaningStaff" placeholder="请选择清洗人员">
                    <el-option v-for="item in getuserlist" :key="item.userId" :label="item.userNickName"
                        :value="item.userName" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">Cancel</el-button>
                <el-button type="primary" @click="submitForm" :loading="isLoading">
                    Confirm
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const dialogFormVisible = ref(false)
const isLoading = ref(false)
const formRef = ref(null)

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    page.value.pageSize = val
    getcleaning()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    page.value.pageindex = val
    getcleaning()
}
const handleClick = (row) => {
    console.log('click', row)
}

const tableData = ref([
    {
        cleaningId: 0,
        itemName: '',
        itemCause: '',
        planTime: '',
        cleaningStaff: '',
        remark: ''
    }
])
const form = reactive({
    cleaningId: 0,
    itemName: '',
    itemCause: '',
    planTime: '',
    cleaningStaff: '',
    remark: ''
})

const rules = reactive({
    itemName: [
        { required: true, message: '请选择设备名称', trigger: 'change' }
    ],
    itemCause: [
        { required: true, message: '请输入清洗原因', trigger: 'blur' }
    ],
    planTime: [
        { required: true, message: '请输入时间', trigger: 'blur' },
        { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: 'blur' }
    ],
    cleaningStaff: [
        { required: true, message: '请选择清洗人员', trigger: 'change' }
    ]
})

onMounted(() => {
    getcleaning()
    getshebei()
    getuser()
})

const getuserlist = ref([{
    userId: 0,
    userName: "",
    password: "",
    userNickName: ""
}])
const getuser = () => {
    axios.get('http://10.223.8.6:8000/read/api/User/GetUse').then((response) => {
        getuserlist.value = response.data.data
    })
}

const getshebeilist = ref([{
    id: 0,
    equipment_Name: "",
    model: "",
    manufacturer: "",
    purchase_Date: "",
    status: ""
}])
const getshebei = () => {
    axios.get('http://8.154.44.176:8000/p-read/api/Equipment/GetEquipment').then((response) => {
        getshebeilist.value = response.data.data
    })
}

const page = ref({
    pageindex: 1,
    pageSize: 10,
    totalCount: 0,
    totalPage: 0
})

const getcleaning = async () => {
    try {
        const res = await axios.get('http://8.154.44.176:8000/g-read/api/Cleaning/Handle', {
            params: {
                pageindex: page.value.pageindex,
                pageSize: page.value.pageSize
            }
        })
        tableData.value = res.data.data
        page.value.totalCount = res.data.totalCount
        page.value.totalPage = res.data.totalPage
    } catch (error) {
        console.error(error)
    }
}

const handleDelete = async (row) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认要删除这条记录吗？',
            '温馨提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        if (confirmResult === 'confirm') {
            await axios.post('https://localhost:7229/api/Cleaning/DeleteCleaning', {
                cleaningId: row.cleaningId
            }).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success('删除成功')
                    tableData.value = tableData.value.filter((item) => item.cleaningId !== row.cleaningId)
                    if (tableData.value.length === 0 && page.value.pageindex > 1) {
                        page.value.pageindex--
                        getcleaning()
                    }
                } else {
                    ElMessage.error('删除失败，请稍后重试')
                }
            })
        }
    } catch (error) {
        if (error instanceof Error && error.name === 'CancelError') {
            ElMessage.info('已取消删除操作')
        } else {
            ElMessage.error('删除失败，请稍后重试')
            console.error(error)
        }
    }
}

const handleEdit = (row) => {
    form.cleaningId = row.cleaningId
    form.itemName = row.itemName
    form.itemCause = row.itemCause
    form.planTime = row.planTime
    form.cleaningStaff = row.cleaningStaff
    form.remark = row.remark
    dialogFormVisible.value = true
}

const submitForm = async () => {

    axios.post('https://localhost:7229/api/Cleaning/UpdateCleaning', form)
        .then((res) => {
            if (res.data.code === 200) {
                ElMessage.success('提交成功')
                dialogFormVisible.value = false
                getcleaning()
            } else {
                ElMessage.error('提交失败，请稍后重试')
            }
        })
        .catch((error) => {
            ElMessage.error('提交失败，请稍后重试')
            console.error(error)
        })
        .finally(() => {
            isLoading.value = false
        })
}

</script>